#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <termios.h>
#include <time.h>
#include <sys/ioctl.h>
#include <sys/select.h>
#include <poll.h>

/*
#ifndef __VERSION_NO_H__
#define __VERSION_NO_H__
#define MAJOR_VERSION 1
#define MINOR_VERSION 0
#define BUILD_VERSION 1
#define  STRPRODUCTVER "v1.2.3"
#endif
*/
static int get_line(char * to,char *from)
{
    int count = 0;
    if(from==NULL)
    {
        return -1;
    }
    while((*from!='\n')&&(*from!=0))
    {
        *to++ = *from++;
        count++;
    }
    *to  ='\n';
    count++;
    return count;
}
int main( int argc, char* argv[] )
{
    int error,i;
    int major_ver = 0;
    int minor_ver = 0;
    int build_ver  =0; 
    int fsize = 0;
    char *tmp=NULL;
    char *fbuf =NULL;
    char *pos =NULL;
    char str_buf[1024];
    int ret;
    size_t len = 0;
    size_t count =1;
    int read_len;
    FILE *fp = NULL;
    struct stat st;
    fp = fopen(argv[1], "rb+");
  //  fp = fopen("version_no.h","rb+");
    if ( fp == NULL )
    {
        perror("fopen\n");
        return -1;
    }
    fseek(fp,0,SEEK_SET);
   ret = fstat(fileno(fp),&st);
   if(ret<0)
   {
        perror("fstat");
        return -1;
   }
   fsize = st.st_size;
   fbuf = (char *)malloc(fsize+1);
   tmp = fbuf ;
   if(fbuf==NULL)
   {
       perror("malloc");
       fclose(fp);
       return -1;
   }
   memset(fbuf,0,fsize+1);
   while(fread(fbuf,100,1,fp))
    {
        fbuf+=100;
   }
   fbuf = tmp;
  fseek(fp,0,SEEK_SET);
  
  for(i=0;i<st.st_size;)
  {
        read_len = get_line(str_buf,fbuf);
         pos=strstr(str_buf,"MAJOR_VERSION");
         if(pos!=NULL)
        {
             while((*pos++)!=' ');
             major_ver = atoi(pos);
         }
         pos=strstr(str_buf,"MINOR_VERSION");
         if(pos!=NULL)
        {
             while((*pos++)!=' ');
             minor_ver = atoi(pos);
         }
         
         pos=strstr(str_buf,"BUILD_VERSION");
         if(pos!=NULL)
        {
             while((*pos++)!=' ');
             build_ver = atoi(pos);
             build_ver++;
             sprintf(pos,"%d\n",build_ver);
         }
         
         pos=strstr(str_buf,"STRPRODUCTVER");
         if(pos!=NULL)
        {
             while((*pos++)!=' ');
             sprintf(pos,"\"v%d.%d.%d\"\n",major_ver,minor_ver,build_ver);
         }
         len = strlen(str_buf);
         fwrite(str_buf,len,count,fp);

        fbuf+=read_len;
        memset(str_buf,0,sizeof(str_buf));
        i+=read_len;
    }
    free(tmp);
    tmp = NULL;
    fbuf = NULL;
    fclose(fp);
    return 0;
}

